package com.kaifamiao.servlet;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.logging.Logger;

public class ConfigurationServlet implements Servlet {

    public static final String NAME = "encoding";
    public static final String DEFAULT = "UTF-8";
    private final Logger logger = Logger.getLogger( this.getClass().getName() );

    private ServletConfig config;
    private String encoding;

    @Override
    public void init(ServletConfig config) throws ServletException {
        logger.info( String.format( "正在初始化[%s]", config.getServletName() ) );
        this.config = config ;
        // 根据参数名称获得初始化参数的值
        encoding = config.getInitParameter( NAME );
        // 当初始化参数值为 空 或 空白 则使用默认值，否则使用用户设置的值
        encoding = encoding == null || encoding.isBlank() ? DEFAULT : encoding;
        // 若JVM支持用于设置的编码则使用用于设置的编码，否则使用默认值
        encoding = Charset.isSupported( encoding ) ? encoding : DEFAULT;
    }

    @Override
    public void service(ServletRequest req, ServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding( encoding );
        resp.setCharacterEncoding( encoding );
        resp.setContentType( "text/html; charset=" + encoding );
        PrintWriter out = resp.getWriter();
        // 获得所有初始化参数名称
        Enumeration<String> names = config.getInitParameterNames();
        Iterator<String> itor = names.asIterator();
        while( itor.hasNext() ) {
            String name = itor.next();
            String value = config.getInitParameter( name );
            out.println("<p align='center'>" + name + " : " + value + "</p>");
        }
    }

    @Override
    public void destroy() {

    }

    @Override
    public String getServletInfo() {
        return config.getServletName();
    }

    @Override
    public ServletConfig getServletConfig() {
        return config;
    }
}
